import axios from "axios";
import qs from 'qs';
import {
  Message
} from 'element-ui';


const baseURL = window.baseUrl;
/**
 * 创建axios实例，post请求为json请求
 */
const instance = axios.create({
  baseURL,
  'Content-Type': 'application/json; charset=utf-8',
  timeout: 1000 * 10,
//   withCredentials:true,
});

/**
 * 请求拦截器
 * 每次请求前，如果存在token则在请求头中携带token
 */

instance.interceptors.request.use(config => {
  
  return config;
}, error => {
  return error
})
/**
 * 响应拦截
 */
instance.interceptors.response.use(response => {
  return response;
}, error => {
  console.log('连接超时，请检查网络')
//   Message({
//     message: "连接超时，请检查网络",
//     type: "warning"
//   });
})


function ajax(type, url, options) {
  if (!options) {
    options = {};
  }
  return new Promise((resolve, reject) => {
    instance({
      method: type,
      headers:{
        'Accept':'application/json',
        'Authorization':'Bearer 12345678',
        'Content-Type': 'application/json; charset=utf-8'
      },
      url: url,
      params: type === 'get' || type === 'delete' ? options : null,
      data: type !== 'get' && type !== 'delete' ? options : null
    }).then((res) => {
      if (res.status === 200) {
        resolve(res.data)
      } else {
        Message({
          message: res.data.message,
          type: "warning"
        });
        reject("request error in " + url)
      }

    }).catch((err) => {
      console.log(err, url)
    })
  })
}


const api = {
  baseURL,
  get(url, options) {
    return ajax("get", url, options);
  },
  post(url, options) {
    return ajax("post", url, options);
  },
  put(url, options) {
    return ajax("put", url, options);
  },
  patch(url, options) {
    return ajax("patch", url, options);
  },
  delete(url, options) {
    return ajax("delete", url, options);
  }
}
export default api